package net.sansi.v3correctserver.service.camera.cameras;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.extern.slf4j.Slf4j;
import net.sansi.v3correctserver.exception.ServiceException;
import net.sansi.v3correctserver.service.camera.Camera;

import java.nio.file.Path;
import java.util.concurrent.TimeUnit;

/**
 * Created by Fang
 * create time : 2024/11/25
 * IDE : IntelliJ IDEA
 */

@Slf4j
public class Canon7DExeCamera extends CanonExeCameraBase {

    @Override
    public String getName() {
        return "Canon_7D_EXE_CR2";
    }

    @Override
    public String getSuffix() {
        return "CR2";
    }


    @Override
    public boolean checkReady() {
        return true;
    }

    /**
     * 获取默认保存的文件名称
     *
     * @return 文件名称
     */
    @JsonIgnore
    public String getImageName() {
        return "IMG_0001.CR2";
    }

    @Override
    public boolean takePhoto(Camera.Params params, Path savePath) {
        Camera.Params p = params;
        String cameraExeSdkDir = SpringUtil.getProperty("correct.camera-exe-sdk-dir", "D:/cameraSDK/debug/");
        String cameraExeSdkName = SpringUtil.getProperty("correct.camera-exe-sdk-name", "cameraSDKTest.exe");
        Path cameraPath = Path.of(cameraExeSdkDir);
        String cmd = StrUtil.format(
                "cmd /c cd /d {} && {} takePicture {} av {} tv {} iso {}",
                cameraPath.toFile().getAbsoluteFile(),
                cameraExeSdkName,
                getTvItem(p.getTv()).getMs() + 1500,
                p.getAv(),
                getTvItem(p.getTv()).getCode(),
                p.getIso()
        );
        log.info("[camera cmd] {}", cmd);
        try {
            StopWatch watch = new StopWatch("拍照");
            watch.start("拍照");
            Process process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            watch.stop();
            watch.start("移动图片");
            Path imgSrc = cameraPath.resolve(getImageName());
            if (!imgSrc.toFile().exists()) throw new ServiceException("找不到相片! {}", imgSrc.toUri().toString());
            FileUtil.move(imgSrc, savePath, true);
            watch.stop();
            log.info("{}", watch.prettyPrint(TimeUnit.MILLISECONDS));
        } catch (Exception e) {
            throw new ServiceException("相片拍摄失败！[{}]", e.getMessage(), e);
        }
        return true;
    }

}
